import 'bootstrap/dist/css/bootstrap.min.css';
import React, { useState ,useEffect} from 'react';
import { Form, Input, Upload, message, Button, Select, Row, Col, Typography} from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import {postArticle,getCategories} from '../../services/api.js';

const { TextArea } = Input;
const { Option } = Select;
const { Title } = Typography;

export default function PostPage() {
  const [form] = Form.useForm();
  const [imageList, setImageList] = useState([]);
  const [categories, setCategories] = useState([]);
  const navigate = useNavigate();
  useEffect(() => {
  	const fetchCategoryData = async () => {
  	try {
  	        const result = await getCategories();
  	        setCategories(result);
  	    } catch (error) {
  	        message.error('请求分类数据时出错');
  	    }
  	};
  fetchCategoryData();
  }, []); 
  const onFinish = async (values) => {
    try {
      const formData = new FormData();
      formData.append('articleCategoryId', values.category);
      formData.append('articleTitle', values.articleTitle);
      formData.append('articleContent', values.articleContent);
      imageList.forEach((file) => {
        formData.append('files', file.originFileObj);
      });
	 /* formData.forEach((value, key) => {
	    console.log(key, value);
	 }); */
	 const response = await postArticle(formData); 
     if(response){
		 message.success(response);
		 navigate('/home');
	 }
    } catch (error) {
      message.error('发布失败');
      console.error('Upload failed:', error);
    }
  };

  const onFinishFailed = (errorInfo) => {
    console.log('Failed:', errorInfo);
  };

  const normFile = (e) => {
    if (Array.isArray(e)) {
      return e;
    }
    return e && e.fileList;
  };

  const onChange = ({ fileList: newFileList }) => {
    if (newFileList.length <= 9) {
      setImageList(newFileList);
    } else {
      message.error('最多上传9张图片');
    }
  };

  const beforeUpload = (file) => {
    const isImage = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg' || file.type === 'image/webp';
    if (!isImage) {
      message.error('只能上传图片文件');
      return Upload.LIST_IGNORE; 
    }
    return false;
  };

  const uploadProps = {
    onChange,
    fileList: imageList,
    beforeUpload,
  };

  return (
  <Row justify="center" style={{backgroundColor:'aliceblue',minHeight:'100vh'}} >
    <Col span={12} >
      <Title level={2} style={{ textAlign: 'center', marginBottom: '20px' }}>
        发布文章
      </Title>
      <Form
        form={form}
        name="postForm"
        initialValues={{ remember: true }}
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
      >
        <Form.Item
          label="标题"
          name="articleTitle"
          rules={[{ required: true, message: '请输入标题' }]}
        >
          <Input />
        </Form.Item>
     
        <Form.Item
          label="内容"
          name="articleContent"
          rules={[{ required: true, message: '请输入内容' }]}
        >
          <TextArea rows={4} />
        </Form.Item>
     
        <Form.Item
          label="类别"
          name="category"
          rules={[{ required: true, message: '请选择类别' }]}
        >
          <Select placeholder="选择类别">
		  {categories.map(category => (
			<Option key={category.categoryId} value={category.categoryId}>{category.categoryName}</Option>
		  ))}
          </Select>
        </Form.Item>
     
        <Form.Item
          name="files"
          label="图片"
          valuePropName="fileList"
          getValueFromEvent={normFile}
        >
          <Upload {...uploadProps} multiple={true} listType="picture">
            {imageList.length < 9 && (
              <Button icon={<UploadOutlined />}>点击上传图片</Button>
            )}
          </Upload>
        </Form.Item>
     
        <Form.Item>
        <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
            <Button type="primary" htmlType="submit" style={{ marginRight: '5%' }}>
            发布
            </Button>
            <Button type="primary" ghost onClick={()=>{navigate('/home')}}>
            返回
            </Button>
        </div>
        </Form.Item>
      </Form>
	  
    </Col>
  </Row>
       
  );
}
